import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Progress } from '@/components/ui/progress';
import { Container } from '@/components/common/container';
import { Toolbar, ToolbarActions, ToolbarHeading } from '@/layouts/demo1/components/toolbar';
import { Edit, ArrowLeft, Users, Calendar, DollarSign, Target, AlertTriangle } from 'lucide-react';

const ProjectDetailPage = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [project, setProject] = useState(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    fetchProjectDetail();
  }, [id]);

  const fetchProjectDetail = async () => {
    setLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // 模拟项目详情数据
      const mockProject = {
        id: parseInt(id),
        project_code: 'PRJ-2024-001',
        project_name: '电商平台开发项目',
        project_type: '研发',
        priority: '高',
        status: '执行中',
        manager_name: '张三',
        client_info: 'ABC公司',
        start_date: '2024-01-15',
        end_date: '2024-06-30',
        progress_percentage: 65,
        budget: 500000,
        spent_budget: 325000,
        description: '开发一个现代化的电商平台，包含用户管理、商品管理、订单管理、支付系统、物流管理等功能模块。项目采用微服务架构，使用React前端和Node.js后端技术栈。',
        objectives: '1. 提升用户体验，实现流畅的购物流程\n2. 提高系统性能，支持高并发访问\n3. 增加销售转化率，优化转化漏斗\n4. 建立完善的会员体系\n5. 实现多渠道销售支持',
        risk_level: '中',
        team_members: ['张三', '李四', '王五', '赵六', '钱七', '孙八'],
        tasks_count: 24,
        completed_tasks: 16,
        issues_count: 3,
        resolved_issues: 2
      };
      
      setProject(mockProject);
    } catch (error) {
      console.error('获取项目详情失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const getStatusBadgeVariant = (status) => {
    switch (status) {
      case '立项': return 'secondary';
      case '执行中': return 'default';
      case '验收': return 'success';
      case '结项': return 'outline';
      case '暂停': return 'destructive';
      default: return 'secondary';
    }
  };

  const getPriorityBadgeVariant = (priority) => {
    switch (priority) {
      case '高': return 'destructive';
      case '中': return 'default';
      case '低': return 'secondary';
      default: return 'secondary';
    }
  };

  const getRiskBadgeVariant = (riskLevel) => {
    switch (riskLevel) {
      case '高': return 'destructive';
      case '中': return 'default';
      case '低': return 'success';
      default: return 'secondary';
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="flex items-center gap-2">
          <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
          <span>加载中...</span>
        </div>
      </div>
    );
  }

  if (!project) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <h2 className="text-xl font-semibold mb-2">项目不存在</h2>
          <p className="text-muted-foreground mb-4">该项目可能已被删除或不存在</p>
          <Button onClick={() => navigate('/project-management/project-list')}>
            返回项目列表
          </Button>
        </div>
      </div>
    );
  }

  return (
    <>
      <Container>
        <Toolbar>
          <ToolbarHeading
            title="项目详情"
            description={`${project.project_name} - ${project.project_code}`}
          />
          <ToolbarActions>
            <Button variant="outline" onClick={() => navigate('/project-management/project-list')}>
              <ArrowLeft className="size-4 me-2" />
              返回列表
            </Button>
            <Button onClick={() => navigate(`/project-management/project-form/${project.id}`)}>
              <Edit className="size-4 me-2" />
              编辑项目
            </Button>
          </ToolbarActions>
        </Toolbar>
      </Container>

      <Container>
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* 主要信息 */}
          <div className="lg:col-span-2 space-y-6">
            {/* 基本信息 */}
            <Card>
              <CardHeader>
                <CardTitle>基本信息</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <label className="text-sm font-medium text-muted-foreground">项目编号</label>
                    <p className="font-mono">{project.project_code}</p>
                  </div>
                  <div>
                    <label className="text-sm font-medium text-muted-foreground">项目类型</label>
                    <p>{project.project_type}</p>
                  </div>
                  <div>
                    <label className="text-sm font-medium text-muted-foreground">项目状态</label>
                    <div className="mt-1">
                      <Badge variant={getStatusBadgeVariant(project.status)}>
                        {project.status}
                      </Badge>
                    </div>
                  </div>
                  <div>
                    <label className="text-sm font-medium text-muted-foreground">优先级</label>
                    <div className="mt-1">
                      <Badge variant={getPriorityBadgeVariant(project.priority)}>
                        {project.priority}
                      </Badge>
                    </div>
                  </div>
                  <div>
                    <label className="text-sm font-medium text-muted-foreground">风险等级</label>
                    <div className="mt-1">
                      <Badge variant={getRiskBadgeVariant(project.risk_level)}>
                        {project.risk_level}
                      </Badge>
                    </div>
                  </div>
                  <div>
                    <label className="text-sm font-medium text-muted-foreground">项目负责人</label>
                    <p>{project.manager_name}</p>
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* 项目描述 */}
            <Card>
              <CardHeader>
                <CardTitle>项目描述</CardTitle>
              </CardHeader>
              <CardContent>
                <p className="text-sm leading-relaxed whitespace-pre-line">
                  {project.description}
                </p>
              </CardContent>
            </Card>

            {/* 项目目标 */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Target className="size-5" />
                  项目目标
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-2">
                  {project.objectives.split('\n').map((objective, index) => (
                    <div key={index} className="flex items-start gap-2">
                      <div className="w-2 h-2 bg-primary rounded-full mt-2 flex-shrink-0"></div>
                      <p className="text-sm">{objective}</p>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          </div>

          {/* 侧边栏信息 */}
          <div className="space-y-6">
            {/* 进度概览 */}
            <Card>
              <CardHeader>
                <CardTitle>进度概览</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div>
                  <div className="flex justify-between text-sm mb-2">
                    <span>项目进度</span>
                    <span>{project.progress_percentage}%</span>
                  </div>
                  <Progress value={project.progress_percentage} className="w-full" />
                </div>
                
                <div className="grid grid-cols-2 gap-4 text-center">
                  <div className="p-3 bg-secondary/50 rounded-lg">
                    <div className="text-2xl font-bold text-primary">{project.completed_tasks}</div>
                    <div className="text-xs text-muted-foreground">已完成任务</div>
                  </div>
                  <div className="p-3 bg-secondary/50 rounded-lg">
                    <div className="text-2xl font-bold text-primary">{project.tasks_count}</div>
                    <div className="text-xs text-muted-foreground">总任务数</div>
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* 时间信息 */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Calendar className="size-5" />
                  时间信息
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-3">
                <div>
                  <label className="text-sm font-medium text-muted-foreground">开始时间</label>
                  <p className="text-sm">{project.start_date}</p>
                </div>
                <div>
                  <label className="text-sm font-medium text-muted-foreground">结束时间</label>
                  <p className="text-sm">{project.end_date}</p>
                </div>
                <div>
                  <label className="text-sm font-medium text-muted-foreground">客户信息</label>
                  <p className="text-sm">{project.client_info || '暂无'}</p>
                </div>
              </CardContent>
            </Card>

            {/* 预算信息 */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <DollarSign className="size-5" />
                  预算信息
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-3">
                <div>
                  <label className="text-sm font-medium text-muted-foreground">项目预算</label>
                  <p className="text-lg font-semibold">¥{project.budget?.toLocaleString()}</p>
                </div>
                <div>
                  <label className="text-sm font-medium text-muted-foreground">已使用预算</label>
                  <p className="text-sm">¥{project.spent_budget?.toLocaleString()}</p>
                </div>
                <div>
                  <label className="text-sm font-medium text-muted-foreground">预算使用率</label>
                  <div className="flex items-center gap-2">
                    <Progress 
                      value={(project.spent_budget / project.budget) * 100} 
                      className="flex-1" 
                    />
                    <span className="text-sm">
                      {Math.round((project.spent_budget / project.budget) * 100)}%
                    </span>
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* 团队成员 */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Users className="size-5" />
                  团队成员
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="flex flex-wrap gap-2">
                  {project.team_members.map((member, index) => (
                    <Badge key={index} variant="secondary">
                      {member}
                    </Badge>
                  ))}
                </div>
              </CardContent>
            </Card>

            {/* 问题统计 */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <AlertTriangle className="size-5" />
                  问题统计
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-2 gap-4 text-center">
                  <div className="p-3 bg-destructive/10 rounded-lg">
                    <div className="text-2xl font-bold text-destructive">{project.issues_count}</div>
                    <div className="text-xs text-muted-foreground">总问题数</div>
                  </div>
                  <div className="p-3 bg-success/10 rounded-lg">
                    <div className="text-2xl font-bold text-success">{project.resolved_issues}</div>
                    <div className="text-xs text-muted-foreground">已解决问题</div>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        </div>
      </Container>
    </>
  );
};

export default ProjectDetailPage; 